<template>
  <el-dialog
      :modelValue="modelValue"
      @update:modelValue="handleModelValueUpdate"
      title="生成运输订单"
      width="62%"
      @close="handleClose"
  >
    <!-- 订单信息表格 -->
    <el-table
        :data="orders"    style="width: 100%; height: 100%;"
        v-if="orders.length > 0"
        class="full-height-table"
    >
      <el-table-column
          prop="allocationNo"
          label="调拨单号"
          min-width="180"
      />
      <el-table-column
          prop="origin"
          label="发货地"
          min-width="180"
      />
      <el-table-column
          prop="destination"
          label="目的地"
          min-width="180"
      />
      <el-table-column
          prop="warehouseNo"
          label="仓库编号"
          min-width="180"
      />
      <el-table-column
          prop="allocationDate"
          label="调拨日期"
          min-width="180"
      />
    </el-table>

    <!-- 调拨单临时信息表单 -->
    <el-form :model="tempOrder" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="运输订单号">
            <el-input v-model="tempOrder.trackingNumber" disabled />
          </el-form-item>
          <el-form-item label="发货地">
            <el-input v-model="tempOrder.origin" disabled />
          </el-form-item>
          <el-form-item label="目的地">
            <el-input v-model="tempOrder.destination" disabled />
          </el-form-item>
          <el-form-item label="仓库编号">
            <el-input v-model="tempOrder.warehouseNo" disabled />
          </el-form-item>
          <el-form-item label="调拨日期">
            <el-date-picker
                v-model="tempOrder.allocationDate"
                type="datetime"
                placeholder="选择预计到达日期"                style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="预计到达日期">
            <el-date-picker
                v-model="tempOrder.expectedDeliveryTime"
                type="datetime"
                placeholder="选择预计到达日期"                style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="物流商ID">
            <el-input v-model="tempOrder.carrierNo" disabled />
            <el-button type="primary" size="small" @click="showCarrierSelection">选择物流商</el-button>
          </el-form-item>
          <el-form-item label="物流商名称">
            <el-input v-model="tempOrder.carrierName" disabled />
          </el-form-item>
          <el-form-item label="重量">
            <el-input-number
                v-model="tempOrder.weight"
                :min="0"
                placeholder="请输入重量"                style="width: 100%;"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重量单位">
            <el-select v-model="tempOrder.weightUnit" placeholder="选择重量单位" style="width: 100%;">
              <el-option label="吨" value="t"></el-option>
              <el-option label="千克" value="kg"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运输数量">
            <el-input v-model="tempOrder.transportQuantity" disabled />
          </el-form-item>
          <el-form-item label="状态">
            <el-input v-model="tempOrder.state" disabled />
          </el-form-item>
          <el-form-item label="物流费用">
            <el-input-number
                v-model="tempOrder.logisticsFee"
                :min="0"
                :precision="2"
                placeholder="请输入物流费用（元）"                style="width: 100%;"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="创建日期">
            <el-input :value="formatDate(tempOrder.createdTime)" disabled />
          </el-form-item>
          <el-form-item label="修改日期">
            <el-input :value="formatDate(tempOrder.modifiedDate)" disabled />
          </el-form-item>
          <el-form-item label="修改人">
            <el-input v-model="tempOrder.modifiedBy" disabled />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="tempOrder.remarks" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 物流商选择对话框 -->
    <el-dialog
        title="选择物流商"
        v-model="carrierSelectionVisible"
        width="80%"
        append-to-body
    >
      <el-row :gutter="20" type="flex" justify="start">
        <el-col :span="6">
          <el-input
              v-model="filters.carrierNo"
              placeholder="物流商ID"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="filters.carrierName"
              placeholder="物流商名称"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-select
              v-model="filters.carrierType"
              placeholder="物流商类型"
              clearable
              size="small"
          >
            <el-option label="第三方平台" value="0" />
            <el-option label="平台提供" value="1" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="filters.carrierAddress"
              placeholder="物流商地址"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="filters.contactPerson"
              placeholder="联系人姓名"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-button
              type="primary"
              size="small"
              @click="applyFilters"
              style="margin-top: 4px;"
          >
            查询
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="resetFilters"
              style="margin-top: 4px;"
          >
            重置
          </el-button>
        </el-col>
      </el-row>

      <!-- 物流商信息列表 -->
      <el-table
          :data="currentCarrierList"
          @current-change="handleCurrentChange"
          highlight-current-row
          style="width: 100%"
          :row-class-name="tableRowClassName"
      >
        <el-table-column
            prop="carrierNo"
            label="物流商编号"
            width="120"
        />
        <el-table-column
            prop="carrierName"
            label="物流商名称"
            width="180"
        />
        <el-table-column
            prop="carrierType"
            label="物流商类型"
            :formatter="carrierTypeFormatter"
        />
        <el-table-column
            prop="carrierAddress"
            label="物流商地址"
            width="200"
        />
        <el-table-column
            prop="contactPerson"
            label="联系人姓名"
            width="150"
        />
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          v-if="filteredCarrierList.length > 0"
          :page-size="pageSize"
          :total="filteredCarrierList.length"
          :current-page="currentPage"
          @current-change="handlePageChange"
          layout="prev, pager, next, jumper"
          style="margin-top: 10px; text-align: right;"
      />

      <!-- 确定按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="carrierSelectionVisible = false">取消</el-button>
        <el-button type="primary" @click="selectCarrier">确定</el-button>
      </div>
    </el-dialog>

    <!-- 确定和取消按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { listCarrierInfo } from '@/api/delivery/carrier.js';
import { generateTrackingNumber } from '@/api/delivery/allocation.js';
import { addOperatorTransport, addOperatorTransportDetail } from "@/api/delivery/operatorTransport.js";
import { getAllocationDetail, updateAllocation } from "@/api/delivery/allocation.js";
import { ElMessage } from "element-plus";

export default {
  props: {
    modelValue: {
      type: Boolean,
      required: true,
    },
    orders: {
      type: Array,
      default: () => []
    },
  },
  setup(props, { emit }) {
    const carrierList = ref([]);
    const selectedCarrier = ref(null);
    const filters = ref({
      carrierNo: '',
      carrierName: '',
      carrierType: '',
      carrierAddress: '',
      contactPerson: ''
    });
    const filteredCarrierList = ref([]);
    const currentCarrierList = ref([]);
    const pageSize = 5;
    const currentPage = ref(1);
    const carrierSelectionVisible = ref(false);
    const tempOrder = ref([]);

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const generateTrackingNumberAndSet = async () => {
      try {
        const response = await generateTrackingNumber();
        tempOrder.value.trackingNumber = response.trackingNumber;
      } catch (error) {
        console.error('生成跟踪号失败:', error);
        ElMessage.error('生成跟踪号失败');
      }
    };

    watch(
        () => props.modelValue,
        (newValue) => {
          if (newValue) {
            if (props.orders.length > 0) {
              const latestAllocationDate = new Date(Math.max(...props.orders.map(order => new Date(order.allocationDate))));
              const earliestExpectedDeliveryTime = new Date(Math.min(...props.orders.map(order => new Date(order.expectedDeliveryTime || latestAllocationDate)))); // 新增计算最早日期
              const totalWeight = props.orders.reduce((sum, order) => sum + (order.weight || 0), 0);
              const totalTransportQuantity = props.orders.reduce((sum, order) => sum + (order.transportQuantity || 0), 0);

              tempOrder.value = {
                ...props.orders[0], // 取第一个订单作为临时订单信息
                allocationDate: latestAllocationDate.toISOString(),
                expectedDeliveryTime: earliestExpectedDeliveryTime.toISOString(), // 新增字段
                weight: totalWeight,
                transportQuantity: totalTransportQuantity,
                carrierNo: '',
                carrierName: '',
                remarks: '',
                logisticsFee: null,
                createdTime: new Date(),
                modifiedDate: null,
                modifiedBy: null,
                state: '未分配运输订单',
              };
            }
            fetchCarrierInfo();
            generateTrackingNumberAndSet(); // 调用生成跟踪号的方法
          }
        }
    );

    const generateTransportOrder = async () => {
      if (Object.keys(tempOrder.value).length > 0) {
        try {
          const order = tempOrder.value;
          const transportData = {
            trackingNumber: order.trackingNumber,
            origin: order.origin,
            destination: order.destination,
            warehouseNo: order.warehouseNo,
            departDate: order.allocationDate,
            departureDate: order.expectedDeliveryTime,
            state: "待确认",
            weight: order.weight,
            weightUnit: order.weightUnit,
            transportQuantity: order.transportQuantity,
            logisticId: order.carrierNo,
            ifAlteration: false,
            logisticsFee: order.logisticsFee,
            customerType: 0,
            generatedDate: order.createdTime,
            updatedDate: order.modifiedDate,
            updatedPerson: order.modifiedBy,
            remarks: order.remarks,
            feeTemp: order.logisticsFee,
            tempRemarks: order.remarks
          };
          console.log('transportData:', transportData);
          const response = await addOperatorTransport(transportData);
          const allocationNos = props.orders.map(order => order.allocationNo);
          console.log('allocationNos:', allocationNos);
          for (const allocationNo of allocationNos) {
            const allocationDetailsResponse = await getAllocationDetail(allocationNo);
            const details = allocationDetailsResponse.data || [];
            console.log('allocationDetailsResponse.data:', allocationDetailsResponse.data);

            for (const detail of details) {
              console.log('detail:', detail);
              const transportDetail = {
                transportDetailId: detail.allocationDetailNo,
                trackingNumber: order.trackingNumber,
                orderNumber: order.orderNo,
                productName: detail.rawProductName,
                productBatch: detail.rawProductBatch,
                type: '货品',
                transportQuantity: detail.transportQuantity,
                origin: detail.origin,
                weight: detail.weight,
                weightUnit: detail.weightUnit,
                state: "未送达",
                generatedDate: new Date(),
              };
              await addOperatorTransportDetail(transportDetail);
            }
          }

          if (response.success) {
            for (const allocationNo of allocationNos) {
              const updatedOrder = props.orders.find(allocation => allocation.allocationNo === allocationNo);
              if (updatedOrder) {
                updatedOrder.state = "已生成运输订单";
                updatedOrder.deliveryCode = order.carrierNo;
                updatedOrder.deliveryName = order.carrierName;
                updatedOrder.trackingNo = order.trackingNumber;

                await updateAllocation(updatedOrder);

                ElMessage.success('运输订单已生成');
                emit('update:modelValue', false);
              } else {
                ElMessage.error('未找到对应的调拨单信息');
              }
            }
          } else {
            ElMessage.error('生成运输订单失败');
          }
        } catch (error) {
          ElMessage.error('生成运输订单时出错');
          console.error('生成运输订单失败:', error);
        }
      } else {
        ElMessage.warning('请先选择要生成运输订单的行');
      }
    };

    const fetchCarrierInfo = async () => {
      try {
        const response = await listCarrierInfo();
        carrierList.value = (response.data || []).filter(carrier => carrier.activeStatus === 1);
        applyFilters();
      } catch (error) {
        console.error('获取物流商信息失败:', error);
      }
    };

    const handleCurrentChange = (val) => {
      selectedCarrier.value = val;
    };

    const handleConfirm = () => {
      if (!tempOrder.value.logisticsFee || tempOrder.value.logisticsFee <= 0) {
        ElMessage.warning('请填写物流费用');
        return;
      }
      if (!tempOrder.value.carrierNo) {
        ElMessage.warning('请选择物流商');
        return;
      }
      generateTransportOrder();
      emit('update:modelValue', false);
    };

    const handleClose = () => {
      emit('update:modelValue', false);
    };

    const handleModelValueUpdate = (newValue) => {
      emit('update:modelValue', newValue);
    };

    const carrierTypeFormatter = (row) => {
      return row.carrierType === 0 ? '第三方平台' : '平台提供';
    };

    onMounted(() => {
      console.log('CarrierSelectionDialog mounted');
    });

    const applyFilters = () => {
      filteredCarrierList.value = carrierList.value.filter(carrier => {
        return (
            (!filters.value.carrierNo || carrier.carrierNo.includes(filters.value.carrierNo)) &&
            (!filters.value.carrierName || carrier.carrierName.includes(filters.value.carrierName)) &&
            (!filters.value.carrierType || carrier.carrierType.toString() === filters.value.carrierType) &&
            (!filters.value.carrierAddress || carrier.carrierAddress.includes(filters.value.carrierAddress)) &&
            (!filters.value.contactPerson || carrier.contactPerson.includes(filters.value.contactPerson))
        );
      });
      updateCurrentCarrierList();
    };

    const resetFilters = () => {
      filters.value = {
        carrierNo: '',
        carrierName: '',
        carrierType: '',
        carrierAddress: '',
        contactPerson: ''
      };
      applyFilters();
    };

    const updateCurrentCarrierList = () => {
      const startIndex = (currentPage.value - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      currentCarrierList.value = filteredCarrierList.value.slice(startIndex, endIndex);
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
      updateCurrentCarrierList();
    };

    const tableRowClassName = ({ row }) => {
      return row === selectedCarrier.value ? 'selected-row' : '';
    };

    const showCarrierSelection = () => {
      carrierSelectionVisible.value = true;
    };

    const selectCarrier = () => {
      if (selectedCarrier.value) {
        tempOrder.value.carrierNo = selectedCarrier.value.carrierNo;
        tempOrder.value.carrierName = selectedCarrier.value.carrierName;
      }
      carrierSelectionVisible.value = false;
    };

    return {
      carrierList,
      selectedCarrier,
      handleConfirm,
      handleClose,
      handleModelValueUpdate,
      handleCurrentChange,
      carrierTypeFormatter,
      filters,
      applyFilters,
      resetFilters,
      filteredCarrierList,
      currentCarrierList,
      pageSize,
      currentPage,
      handlePageChange,
      tableRowClassName,
      generateTransportOrder,
      carrierSelectionVisible,
      tempOrder,
      showCarrierSelection,
      selectCarrier,
      formatDate,
      generateTrackingNumberAndSet,
    };
  },
};
</script>

<style scoped>

.full-height-table {
  height: calc(100% - 20px); /* 减去一些边距 */
}

.card-content p {
  margin-bottom: 1px;
  font-size: 13px;
}

.card-content p strong {
  font-size: 13px;
  color: #333;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  margin-bottom: 10px;
}

.el-input, .el-select {
  margin-bottom: 10px;
}

.el-input__inner, .el-select .el-input__inner {
  font-size: 14px;
  padding: 10px;
}

.el-button {
  margin-top: 10px;
  font-size: 14px;
}

.dialog-with-scroll .el-dialog__body {
  max-height: 400px;
  overflow-y: auto;
}

.selected-row {
  background-color: #ecf5ff;
}

.el-dialog {
  width: 70%;
}
</style>
